from copy import copy
from pypika.dialects import QueryBuilder
from pypika.enums import Dialects 
from pypika.queries import Query
from pypika.terms import ValueWrapper
from pypika.utils import builder
from typing import Any, Optional, Union, Tuple as TypedTuple, List

class DmQuery(Query):
    """
    达梦数据库查询类
    """
    @classmethod 
    def _builder(cls, **kwargs: Any) -> "DmQueryBuilder":
        return DmQueryBuilder(**kwargs)

class DmQueryBuilder(QueryBuilder):
    QUOTE_CHAR = '"'  # 达梦使用双引号作为标识符引用符
    QUERY_CLS = DmQuery
    ALIAS_QUOTE_CHAR = '"'
    QUERY_ALIAS_QUOTE_CHAR = ''

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(dialect=Dialects.ORACLE, **kwargs) # 暂时使用ORACLE方言,后续可以添加DM方言
        self._duplicate_updates = []
        self._ignore_duplicates = False

    def __copy__(self) -> "DmQueryBuilder":
        newone = super().__copy__()
        newone._duplicate_updates = copy(self._duplicate_updates)
        newone._ignore_duplicates = copy(self._ignore_duplicates)
        return newone
    
    @builder
    def for_update(
        self, nowait: bool = False, skip_locked: bool = False, of: TypedTuple[str, ...] = ()
    ) -> "QueryBuilder":
        self._for_update = True
        self._for_update_skip_locked = skip_locked
        self._for_update_nowait = nowait
        self._for_update_of = set(of)

    def get_sql(self, **kwargs: Any) -> str:
        # 达梦数据库不支持 group by 字段别名
        kwargs['groupby_alias'] = False
        return super().get_sql(**kwargs) 